package com.haois.mp.wechat.handler;

import com.haois.mp.wechat.common.BusinessRemind;
import com.haois.mp.database.module.offaccounts.service.UserFollowService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 退订事件处理器
 */
@Component
public class UnSubscribeHandler extends AbstractHandler implements WxMpMessageHandler {
    @Autowired
    private UserFollowService userFollowService;

    @Value("${defined.wxmp.sys-openid}")
    private String sysOpenId;

    private Logger logger = LoggerFactory.getLogger(UnSubscribeHandler.class);

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map, WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException {
        this.execute(wxMpXmlMessage, wxMpService);
        return null;
    }

    @Override
    public String execute(WxMpXmlMessage wxMpXmlMessage, WxMpService wxMpService) throws WxErrorException {
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(wxMpXmlMessage.getFromUser());
        userFollowService.updateUser(wxMpXmlMessage.getFromUser(), null, "取消关注");
        logger.info("openId为[{}]的用户取消关注", wxMpXmlMessage.getFromUser());
        BusinessRemind.remindSubByWx(wxMpService, wxMpUser,sysOpenId);
        return "";
    }
}
